<?php
namespace app\api\exception;

use app\api\base\ApiBase;
use think\exception\Handle;
use think\facade\Log;
use think\Response;
use Throwable;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{
    private $code;
    private $message;
    private $statuscode;


    /**
     * @param \think\Request $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        $this->statuscode = $this->code = 500;

        if($e instanceof ApiBase){//是否异常实例
            $this->code = $e->code;
            $this->message = $e->message;
        }else{
            if (config('app_debug')){
                return parent::render($request, $e); // TODO: Change the autogenerated stub
            }
            $this->code = 500;
            $this->message = $e->getMessage() ?: '很抱歉，服务器内部错误';
            $this->recordErrorLog($e);
        }
        // Http异常
        if ($e instanceof \think\exception\HttpException)
        {
            $this->statuscode = $this->code = $e->getStatusCode();
        }
        $data = [
            'message' => $this->message,
            'errorCode' =>  $this->statuscode,
            'request_url' => $request->url()
        ];
        return json($data,$this->statuscode);

    }
    /**
     * 记录日记
     * @param \Exception $e
     */
    public function recordErrorLog(Throwable $e)
    {
        Log::record($e->getMessage(),'error');
        //Log::record($e->getTraceAsString(), 'error');
    }

}
